#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond  = PTHREAD_COND_INITIALIZER;

void cleanup(void * arg)
{
	pthread_mutex_unlock (&mutex);
}

void * thread0 (void * arg)
{
	pthread_cleanup_push(cleanup, NULL);//thread cleanup handler
	pthread_mutex_lock (&mutex);
	pthread_cond_wait (&cond, &mutex);
	pthread_mutex_unlock (&mutex);
	pthread_cleanup_pop(0);
	pthread_exit(NULL);
}

void * thread1 (void * arg)
{
	sleep(10);
	cout<<"thread1: before lock"<<endl;
	pthread_mutex_lock (&mutex);
	cout<<"thread1: inside lock"<<endl;
	pthread_cond_broadcast (&cond);
	pthread_mutex_unlock (&mutex);
	
	pthread_exit(NULL);
}

int main ()
{
	pthread_t tid[2];
	
	pthread_create(&(tid[0]), NULL, thread0, NULL );
	pthread_create(&(tid[1]), NULL, thread1, NULL );
	
	sleep(5);
	pthread_cancel(tid[0]);
	
	pthread_join(tid[0], NULL);
	pthread_join(tid[1], NULL);
	
	pthread_mutex_destroy (&mutex);
	pthread_cond_destroy (&cond);
	
	return 0;
}
